package com.hsy.crm.web.web.report;

import com.hsy.crm.web.domain.entity.Product;
import com.hsy.crm.web.domain.po.product.ProductExportPo;
import com.hsy.crm.web.service.impl.excel.EProductService;
import com.hsy.crm.web.utils.ExcelUtils;
import com.hsy.crm.web.web.BaseAction;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

/**
 * 商品缓存
 */
@RestController
@RequestMapping("/eimport")
public class ExcelImportAction extends BaseAction {

    Logger logger = LoggerFactory.getLogger(ExcelImportAction.class);

    private static final int SHEET = 0;

    @Autowired
    EProductService eproductService;

    @RequestMapping("/product")
    public String exportProduct(@RequestParam("file") MultipartFile file, Product product) {
        InputStream is = null;
        Workbook workbook = null;
        try {
            is = file.getInputStream();
            //workbook = new XSSFWorkbook(is);
            workbook = WorkbookFactory.create(is);
            String[] properties = {"name",	"barcode","code",	"productTypeNames","unitName","unitRates","model","purchaseRealPrice","saleRealPrice","enableBatchs","enableFines","enableStores","price1","price2","price3","price4","price5","comments"};

            Sheet sheet = workbook.getSheetAt(SHEET);
            List<ProductExportPo> products = ExcelUtils.toList(sheet,properties,3,ProductExportPo.class);

            eproductService.insertProducts(products,product);
            return "<script>parent.eimportComplete();</script>";
        }catch (Exception e){
            logger.info("upload product error",e);
            return "<script>parent.eimportError('"+e.getMessage()+"');</script>";
        }

    }

}
